<?php

namespace app\admin\controller\general;

use app\common\controller\Backend;
use FFMpeg\FFMpeg;
/**
 * 附件管理
 *
 * @icon   fa fa-circle-o
 * @remark 主要用于管理上传至本服务的上传数据
 */
class videochoose extends Backend
{

    /**
     * @var \app\common\model\Attachment
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Attachment');
        $this->view->assign("mimetypeList", \app\common\model\Attachment::getMimetypeList());
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法

        if ($this->request->isAjax()) {
            $id = $this->request->request('id');
            $files_path = '/upload/video';
            $files = scandir($files_path);
            $total = count($files);
            $list =[];
            foreach ($files as $name) {
                $ffmpeg = FFMpeg::create();
                // 指定视频文件路径
                $videoPath = $files_path.'/'.$name;
                // 打开视频文件
                $video = $ffmpeg->open($videoPath);
                // 获取视频时长（以秒为单位）
                $seconds = $video->getStreams()->videos()->first()->get('duration');
                $list[]=[
                    'name'=>$name,
                    'seconds'=>$seconds
                ];
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 选择附件
     */
    public function select()
    {
        if ($this->request->isAjax()) {
            return $this->index();
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            $this->error();
        }
        return $this->view->fetch();
    }

    /**
     * 删除附件
     * @param array $ids
     */
    public function del($ids = "")
    {
        if ($ids) {
            \think\Hook::add('upload_delete', function ($params) {
                $attachmentFile = ROOT_PATH . '/public' . $params['url'];
                if (is_file($attachmentFile)) {
                    @unlink($attachmentFile);
                }
            });
            $attachmentlist = $this->model->where('id', 'in', $ids)->select();
            foreach ($attachmentlist as $attachment) {
                \think\Hook::listen("upload_delete", $attachment);
                $attachment->delete();
            }
            $this->success();
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

}
